<?php

namespace App\Console\Commands\SiteLocation;

use App\Models\Common\ConfigModel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class GuanYuanRefreshUrlConfig extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'siteLocation:guanyuan-refresh-url';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '通过系统配置 拿到观远刷新url并在指定时间刷新';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        //获得当前时间 (H:i)
        $time = date('H:i');
        //解析config配置
        $configJson = ConfigModel::query()
            ->where('module', 'guanYuan')
            ->where('name', 'refreshUrl')
            ->value('value');

        if (!$configJson) {
            return;
        }
        $configArr = json_decode($configJson, true);

        //循环所有配置  寻找规则
        foreach ($configArr as $config) {
            //判断有没有要更新的URL
            if (in_array($time, $config['refreshTime'])) {
                //存在要更新的url
                foreach ($config['url'] as $url) {
                    $res = Http::withOptions([
                        'http_errors' => false,
                    ])->withHeaders([
                        'accept' => 'application/json, text/plain, */*',
                    ])->get($url)->json();
                    Log::info('观远URL刷新成功：' . json_encode(['url' => $url, 'res' => $res], JSON_UNESCAPED_UNICODE));
                }
            }

            //判断有没有要执行的脚本
            if (isset($config['runScript'])) {
                foreach ($config['runScript'] as $script) {
                    if (in_array($time, $script['runTime'])) {
                        //存在要跑的脚本
                        Artisan::call($script['name']);
                        Log::info('执行脚本成功：' . json_encode($script, JSON_UNESCAPED_UNICODE));
                    }
                }
            }
        }



    }
}
